﻿using System;
using System.ComponentModel.Composition;
using Cubicle.Core.Interfaces;

namespace Cubicle.Core.Processors.Parameter
{
    [Export("Cubicle.Processors.Parameter.ValueToDoubleArrayParameterResolver", typeof(IProcessor<ParameterRequest>))]
    [ExportMetadata("Name", "ValueToDoubleArrayParameterResolver")]
    [ExportMetadata("Description", "Resolves a single parameter to a double array.")]
    public class ValueToDoubleArrayParameterResolver : ConditionalProcessor<ParameterRequest>
    {
        [Import]
        private ParameterProcessor _parameterResolver;

        public override bool Condition(ParameterRequest request)
        {
            var valueType = request.SourceType;
            return!valueType.IsArray
                   && request.TargetType.IsArray
                   && request.TargetType.GetArrayRank() == 2;
        }

        public override ParameterRequest ConditionalProcess(ParameterRequest request)
        {
            // Value will come in as a jagged array
            var elemType = request.TargetType.GetElementType();
            var result = Array.CreateInstance(elemType, 1, 1);
            var parRequest = new ParameterRequest(elemType, request.Source);
            _parameterResolver.Process(parRequest);
            result.SetValue(parRequest.Result, 0, 0);
            request.Complete(result);
            return request;
        }

    }
}